<template>
  <el-dialog :visible.sync="visible" title="上传文件" width="50%" @close="handleClose">
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      drag
      action="https://jsonplaceholder.typicode.com/posts/"
      multiple
      :on-success="handleUploadSuccess"
      :before-upload="beforeUpload"
      :on-error="handleUploadError"
      :file-list="fileList"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传docx文件，且不超过5MB</div>
    </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: "UploadDocumentDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: []
    };
  },
  watch: {
    visible() {
      this.$refs.uploadRef?.clearFiles();
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false);
    },
    handleUploadSuccess(response, file, fileList) {
      // 处理上传成功的文件
      console.log('File uploaded successfully:', file);
      this.fileList.push(file);
    },
    beforeUpload(file) {
      const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      const isLt5MB = file.size / 1024 / 1024 < 5;

      if (!isDocx) {
        this.$message.error('只能上传docx文件!');
      }
      if (!isLt5MB) {
        this.$message.error('文件大小不能超过5MB!');
      }
      return isDocx && isLt5MB;
    },
    handleUploadError(err, file, fileList) {
      this.$message.error(`文件上传失败: ${err}`);
    },
    handleSubmit() {
      // 提交上传的文件列表
      console.log(this.fileList);
      const uploadedFiles = this.fileList.map(file => ({
        id: Date.now() + Math.floor(Math.random() * 100), // 模拟唯一ID
        name: file.name,
        type: 'Word',
        uploadTime: new Date().toLocaleDateString(),
        creator: 'admin', // 可以从用户信息中获取
        status: '待审核',
        raw: file.raw
      }));
      this.$emit('on-success', uploadedFiles);
      this.handleClose();
    }
  }
};
</script>

<style scoped>
.upload-demo {
  text-align: center;
}
</style>
